const app = getApp()
import {
  getCardList,
  classification,
  getShenyeRecommendDistanceList,
  shenyeDouyinAdvertiseList,
  shenyeDouyinNavigationList,
  indexType,
} from '../../api/index'
const handleAuthorize = require('../../utils/handleAuthorize')
Page({
  data: {
    bannerList: [], //轮播图列表
    swiperCurrent: 0, //轮播图下标
    adverLs: [], //导航分类列表
    navLs: [],
    changeIndex: 0,
    dataList: [], //
    discountImg: 'https://test.coco.milianmeng.net/resource/static/index/discount.png',
    pageSize: 10,
    pageNum: 1,
    listTotal: 0, //列表总数
    loadingType: 0, //加载状态（0：加载中  1：加载完成没有更多）
    loadingShow: true,
    listNull: false, //列表是否为空
    myScroll: 290,
    isFixed: false,
    typeId: '', //类型id
    lat: '', //用户当前纬度
    lnt: '', //用户当前经度
    isToken: false,
    listOne: [],
    listTwo: [],
    loadingOne: false,
    loadingTwo: false,
    indexCssType: 0, // 1:正常首页  2：抽奖页
  },
  onLoad: function () {

    // setTimeout(() => {
    //   tt.createSelectorQuery().select('.main').boundingClientRect(res => {
    //     // console.log('res.top', res)
    //     this.data.myScroll = res.height;
    //   }).exec();
    // }, 300)
    // this.getClassification()
  },
  onShow: function () {
    this.setData({
      isToken: handleAuthorize.validate_login()
    })
    console.log('555isToken',this.data.isToken)
    this.getIndexType()
    // this.getShenyeDouyinAdvertiseList()
    // this.getShenyeDouyinNavigationList()
    // if (this.data.lat == '' && this.data.typeId != '') {
    //   this.getLatLnt()
    // }
  },
  jumpFootprint(){
    tt.navigateTo({
      url: '/pages/subPackages/pagesA/footprint/footprint',
    });
  },
  //获取首页显示样式
  async getIndexType() {
    let res = await indexType()
    this.setData({
      indexCssType: res.result.type
    })
    if (res.result.type == 1) {
      this.getClassification()
      this.getShenyeDouyinAdvertiseList()
      this.getShenyeDouyinNavigationList()
      if (this.data.lat == '' && this.data.typeId != '') {
        this.getLatLnt()
      }
      setTimeout(() => {
        if(this.data.adverLs.length==0){
          tt.createSelectorQuery().select('.main2').boundingClientRect(res => {
            this.data.myScroll = res.height;
          }).exec();
        }else{
          tt.createSelectorQuery().select('.main').boundingClientRect(res => {
            this.data.myScroll = res.height;
          }).exec();
        }
        // tt.createSelectorQuery().select('.main2').boundingClientRect(res => {
        //   // console.log('res.top', res)
        //   this.data.myScroll = res.height;
        // }).exec();
      }, 500)
    }
  },
  //获取轮播图
  async getShenyeDouyinAdvertiseList() {
    let res = await shenyeDouyinAdvertiseList()
    this.setData({
      bannerList: res.result
    })
  },
  //获取分类导航
  async getShenyeDouyinNavigationList() {
    let res = await shenyeDouyinNavigationList()
    this.setData({
      adverLs: res.result
    })
  },
  //监听页面滑动
  onPageScroll(e) {
    if (e.scrollTop > this.data.myScroll) {
      this.data.isFixed = true
    } else {
      this.data.isFixed = false
    }
    this.setData({
      isFixed: this.data.isFixed
    })
  },
  //登录页面跳转
  loginView() {
    tt.navigateTo({
      url: '/pages/login/login',
    });
  },
  //跳转搜索
  jumpSearch() {
    tt.navigateTo({
      url: '/pages/subPackages/pagesA/searchPage/searchPage'
    });
  },
  //分类跳转
  jumpClassify(e) {
    let item = e.currentTarget.dataset.item
    if (item.type == 1) { //跳转配置的链接
      tt.navigateTo({
        url: item.linkUrl,
      });
    } else {
      tt.navigateTo({
        url: '/pages/subPackages/pagesA/classification/classification?id=' + item.id + '&title=' + item.title
      });
    }

  },
  //nav类型选择
  changeNav(e) {
    let index = e.currentTarget.dataset.index
    let item = e.currentTarget.dataset.item
    this.data.typeId = item.id
    this.setData({
      changeIndex: index
    })
    if (index == 0 && this.data.lat != '') {
      this.setData({
        pageNum: 1,
        loadingType: 0,
        loadingShow: true,
        // dataList:[]
      })
      this.getList()
    } else if (index == 1 && this.data.lat != '') {
      this.setData({
        pageNum: 1,
        loadingType: 0,
        loadingShow: true,
        // dataList:[]
      })
      this.getShenyeRecommendDistanceList()
    } else {
      this.getLatLnt()
    }
    tt.pageScrollTo({
      duration: 0,
      selector: '.content',
      offsetTop: 0,
    });
  },
  //店铺详情跳转
  jumpShopDetail(e) {
    let item = e.currentTarget.dataset.item
    tt.navigateTo({
      url: '/pages/subPackages/pagesA/shopDetail/shopDetail?id=' + item.shopId,
    });
  },
  //跳转卡详情
  jumpcardDetail(e) {
    let item = e.currentTarget.dataset.item
    tt.navigateTo({
      url: '/pages/subPackages/pagesA/cardDetail/cardDetail?id=' + item.id + '&shopId=' + item.shopId,
    });
  },
  //获取定位授权
  async getAddress() {
    try {
      let res = await handleAuthorize.authorizedLocation()
      let determine = res['scope.userLocation']
      if (determine && this.data.lat == '') {
        this.setData({
          mobileSysPositioningNo: true
        })
      } else {
        this.setData({
          mobileSysPositioningNo: false
        })
      }
    } catch (e) {

    }
  },
  // 获取定位经纬度
  async getLatLnt() {
    // console.log('handleAuthorize',handleAuthorize)
    let infoLocation = {}
    try {
      infoLocation = await handleAuthorize.getLocation()
      this.setData({
        lat: infoLocation.latitude,
        lnt: infoLocation.longitude,
      })
      if (this.data.changeIndex == 0) {
        this.getList()
      } else {
        this.getShenyeRecommendDistanceList()
      }
    } catch (e) {
      console.log('失败', e)
      if (this.data.changeIndex == 0) {
        this.getList()
      } else {
        this.getShenyeRecommendDistanceList()
      }
    }
  },
  //获取分类
  async getClassification() {
    let res = await classification();
    this.data.typeId = res.result.id
    this.data.navLs = [{
        id: this.data.typeId,
        value: res.result.name
      },
      {
        id: 999,
        value: '附近推荐'
      }
    ]
    this.setData({
      navLs: this.data.navLs
    })
    if (this.data.typeId != '' && this.data.typeId != undefined) {
      this.getLatLnt()
    }
  },
  //获取推荐列表
  async getList() {
    let parameter = {
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
      classificationId: this.data.typeId,
      lat: this.data.lat,
      lnt: this.data.lnt,
    }
    try {
      let res = await getCardList(parameter);
      this.data.listTotal = res.result.total
      var elData = res.result.records
      if (elData.length == 0) {
        this.data.listNull = true
        this.data.loadingOne = false
      } else {
        this.data.listNull = false
        this.data.loadingOne = true
      }

      if (this.data.pageNum > 1) {
        this.data.listOne = this.data.listOne.concat(elData); //将数据拼接在一起
      } else {
        this.data.listOne = elData
      }

      if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
        this.data.loadingType = 1
      } else {
        this.data.loadingType = 0
      }
      this.setData({
        // dataList: this.data.dataList,
        loadingType: this.data.loadingType,
        listNull: this.data.listNull,
        // loadingShow: this.data.loadingShow
      })
    } catch (e) {
      this.setData({
        listOne: [],
        dataList: [],
        listNull: true,
        loadingShow: false
      })
    }
    this.getDataList()
  },
  //获取附近推荐列表
  async getShenyeRecommendDistanceList() {
    let parameter = {
      pageSize: this.data.pageSize,
      pageNum: this.data.pageNum,
      lat: this.data.lat,
      lnt: this.data.lnt,
    }
    let listNullTwo = false
    try {
      let res = await getShenyeRecommendDistanceList(parameter);
      this.data.listTotal = res.result.total
      var elData = res.result.records
      if (elData.length == 0) {
        listNullTwo = true
        this.data.loadingTwo = false
      } else {
        listNullTwo = false
        this.data.loadingTwo = true
      }

      if (this.data.pageNum > 1) {
        this.data.listTwo = this.data.listTwo.concat(elData); //将数据拼接在一起
      } else {
        this.data.listTwo = elData
      }

      if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
        this.data.loadingType = 1
      } else {
        this.data.loadingType = 0
      }
      this.setData({
        // dataList: this.data.dataList,
        loadingType: this.data.loadingType,
        listNullTwo: listNullTwo,
        // loadingShow: this.data.loadingShow
      })

    } catch (e) {
      this.setData({
        listTwo: [],
        dataList: [],
        listNullTwo: true,
        loadingShow: false
      })
    }
    this.getDataList()
  },
  getDataList() {
    let list = []
    let loadingShow = true
    if (this.data.changeIndex == 0) {
      list = this.data.listOne
      loadingShow = this.data.loadingOne
    } else {
      list = this.data.listTwo
      loadingShow = this.data.loadingTwo
    }
    this.setData({
      dataList: list,
      loadingShow: loadingShow
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.pageNum >= Math.ceil(this.data.listTotal / this.data.pageSize)) {
      console.log('没有分页')
      this.data.loadingType = 1
    } else {
      this.data.loadingType = 0
      this.data.pageNum++; //每触底一次 page + 1;
      if (this.data.changeIndex == 0) {
        this.getList()
      } else {
        this.getShenyeRecommendDistanceList()
      }

    }
    this.setData({
      loadingType: this.data.loadingType
    })
  },
})